package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.exception.CustomException;
import com.heroCW.bodhiAttic.dto.DishDto;
import com.heroCW.bodhiAttic.dto.SetmealDto;
import com.heroCW.bodhiAttic.entity.Category;
import com.heroCW.bodhiAttic.entity.Dish;
import com.heroCW.bodhiAttic.entity.Setmeal;
import com.heroCW.bodhiAttic.entity.SetmealDish;
import com.heroCW.bodhiAttic.mapper.SetmealMapper;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import com.heroCW.bodhiAttic.service.CategoryService;
import com.heroCW.bodhiAttic.service.DishService;
import com.heroCW.bodhiAttic.service.SetmealDishService;
import com.heroCW.bodhiAttic.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐，同时保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public Boolean saveWithDish(SetmealDto setmealDto) {
        // 保存套餐基本信息
        Boolean[] flags = new Boolean[2];
        flags[0] = this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        // 保存套餐和菜品的关联信息
        flags[1] = setmealDishService.saveBatch(setmealDishes);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;
    }

    /**
     * 删除套餐，同时删除套餐和菜品的关联关系
     *
     * @param ids
     */
    @Override
    @Transactional
    public Boolean removeWithDish(List<Long> ids) {
        Boolean[] flags = new Boolean[2];
        // 查询套餐状态
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        int count = this.count(queryWrapper);
        // 查出数据，不能删除
        if (count > 0) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_DELETE_ERR, "套餐正在售卖中，不能删除");
        }

        // 先删除套餐表中的数据
        flags[0] = this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);

        // 删除关系表的数据
        flags[1] = setmealDishService.remove(lambdaQueryWrapper);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;
    }

    /**
     * 修改套餐状态（启售||停售）
     *
     * @param status
     * @param ids
     */
    @Override
    @Transactional
    public Boolean updateStatus(Integer status, List<Long> ids) {
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Setmeal::getId, ids);
        updateWrapper.set(Setmeal::getStatus, status);

        return this.update(new Setmeal(), updateWrapper);
    }

    /**
     * 获取所有套餐信息并进行分页处理
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public IPage<SetmealDto> getPage(int page, int pageSize, String name) {
        // 创建分页构造器
        IPage<Setmeal> pageInfo = new Page<>(page, pageSize);
        IPage<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(name)) {

            setmealWrapper.like(Setmeal::getName, name);

            List<Long> longList = categoryService.getIdsLikeName(name);

            if (!longList.isEmpty()) {
                setmealWrapper.or();
                setmealWrapper.in(Setmeal::getCategoryId, longList);
            }
        }

        setmealWrapper.orderByDesc(Setmeal::getUpdateTime);

        this.page(pageInfo, setmealWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            // 对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            // 分类id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                // 分类名称
                String categoryName = category.getName();
                // 根据id查询分类对象
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return dtoPage;
    }

    @Override
    public List<Setmeal> getList(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        return this.list(queryWrapper);
    }

    @Override
    @Transactional
    public Boolean updateWithDish(SetmealDto setmealDto) {
        Boolean[] flags = new Boolean[2];

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long setmealId = setmealDto.getId();

        //先根据id把setmealDish表中对应套餐的数据删了
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishService.remove(queryWrapper);
        //然后在重新添加
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        //更新套餐数据
        flags[0] = this.updateById(setmealDto);
        //更新套餐对应菜品数据
        flags[1] = setmealDishService.saveBatch(setmealDishes);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;

    }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
        Setmeal setmeal = this.getById(id);

        if (setmeal == null) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_QUERY_ERR, "暂时无法查询套餐信息，请刷新再试");
        }

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    @Override
    public List<DishDto> getSetmealDish(Long id) {

        //条件构造器
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //手里的数据只有setmealId
        dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        //查询数据
        List<SetmealDish> records = setmealDishService.list(dishLambdaQueryWrapper);
        List<DishDto> dtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //copy数据
            BeanUtils.copyProperties(item, dishDto);
            //查询对应菜品id
            Long dishId = item.getDishId();
            //根据菜品id获取具体菜品数据，这里要自动装配 dishService
            Dish dish = dishService.getById(dishId);
            //其实主要数据是要那个图片，不过我们这里多copy一点也没事
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        return dtoList;
    }
}
